//
//  DFStatusViewModel.swift
//  FlyBlog
//
//  Created by FEI on 16/4/13.
//  Copyright © 2016年 FEI. All rights reserved.
//

import UIKit
import SDWebImage

class DFStatusViewModel: NSObject {

    private var loadStatusing: Bool = false

    static let shareInstance: DFStatusViewModel = DFStatusViewModel()

    private func loadLocalStatuses() {
        let path = NSBundle.mainBundle().pathForResource("statues.json", ofType: nil)!
        let data = NSData(contentsOfFile:path)!

        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
            DFPrint("json:\(json)")
        } catch let error as NSError {
            DFPrint("json序列化异常:\(error)")

        }
    }
    //加载微博数据
    func loadStatus(since_id: Int64,max_id: Int64, laodStatusCallback:(statuses: [DFStatus]?, error: NSError?) -> ()) {

        if loadStatusing == true {
           DFPrint("有人加载微博数据")
            let error = DFNetworkErrorEnum.RepeatLoadStatus.error()
            laodStatusCallback(statuses: nil,error: error)
            return
        }

        loadStatusing = true

        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        var parameters: [String: AnyObject] = ["access_token":DFUserAccountModel.shareInstance.userAccount!.access_token!]


        if since_id > 0 {
            parameters["since_id"] = NSNumber(longLong: since_id)
        }else if max_id > 0 {
            parameters["max_id"] = NSNumber(longLong: max_id)
        }

        let debug = false
        if debug {
            loadLocalStatuses()
            return
        }

        //TODO:测试加载数据库微博数据
        HMStatusDAL.sharedDAL.loadCacheStatus(since_id, max_id: max_id) { (status) -> () in
            if status == nil || status?.count == 0 {
                print("本地数据库没有数据")
                return
            }
            print("从本地数据库加载到了微博数据:\(status)")
        }

        DFNetworkTool.shareInstance.GET(urlString, parameters: parameters, progress: nil, success: { (task, responseObject) -> Void in

            self.loadStatusing = false

            if let dic = responseObject as? [String : AnyObject],let statusesDic = dic["statuses"] as? [[String : AnyObject]] {
                HMStatusDAL.sharedDAL.saveCacheStatus(statusesDic)
                var statusModels: [DFStatus] = []
                for dic in statusesDic {
                    let status = DFStatus(dict: dic)
                    statusModels.append(status)

                }

                self.cacheWebImage(statusModels, loadStatusCallback: laodStatusCallback)
//                laodStatusCallback(statuses:statusModels,error: nil)

            }

            }) { (task, error) -> Void in
             laodStatusCallback(statuses:nil,error: error)
        }
    }

    //MARK:缓存微博图片
    private func cacheWebImage(statuses: [DFStatus],loadStatusCallback: (statuses: [DFStatus]?,error: NSError?) -> () ){
        let group = dispatch_group_create()

        for status in statuses {
            var downloadURLs: [NSURL]?

            downloadURLs = status.storePictureURLs

            if downloadURLs == nil {
                downloadURLs = status.retweeted_status?.storePictureURLs
            }

            if let urls = downloadURLs {
                if urls.count == 1 {
                    let url = urls.first!
                    dispatch_group_enter(group)
                    SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (image, error, _, _, _) -> Void in
                        dispatch_group_leave(group)

                        if error != nil {
                            return
                        }
                    })

                }
            }
        }

        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            loadStatusCallback(statuses: statuses, error: nil)
        }
    }

    //MARK:发微博
    func sendStatus(text: String,image: UIImage?, sendStatusCallback:(error: NSError?) -> ()) {
        guard let access_token = DFUserAccountModel.shareInstance.userAccount?.access_token else {
            let error = DFNetworkErrorEnum.AccessTokenEmpty.error()
            sendStatusCallback(error: error)
            return
        }

        let parameters = [
            "access_token" : access_token,
            "status" : text
        ]

        if image == nil {

            let urlString = "https://api.weibo.com/2/statuses/update.json"

            DFNetworkTool.shareInstance.POST(urlString, parameters: parameters, progress: nil, success: { (_, responseObject) -> Void in
                sendStatusCallback(error: nil)
                }) { (_, error) -> Void in
                    sendStatusCallback(error: error)
            }


        }else {
            let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"

            DFNetworkTool.shareInstance.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formdata) -> Void in
                let data = UIImagePNGRepresentation(image!)!

                formdata.appendPartWithFileData(data, name: "pic", fileName: "", mimeType: "image/png")
                }, progress: nil, success: { (_, responseObject) -> Void in
                    sendStatusCallback(error: nil)
                }, failure: { (_, error) -> Void in
                    sendStatusCallback(error: error)
            })
        }
    }
}
